
<script setup>
import { ref } from 'vue'
import  PageContainer  from '@/components/PageContainer.vue'
import { ElMessage } from 'element-plus'
import { userUpdatePwdService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
const router = useRouter()
const userStore = useUserStore()
const pwdFormRef = ref()
// 表单绑定字段
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

// 表单校验规则
const rules = {
  old_pwd: [
    { required: true, message: '原密码不能为空', trigger: 'blur' },
    {
      min: 6,
      max: 15,
      message: '原密码长度需在 6-15 位之间',
      trigger: 'blur'
    }
  ],
  new_pwd: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    {
      min: 6,
      max: 15,
      message: '新密码长度需在 6-15 位之间',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value === pwdForm.value.old_pwd) {
          callback(new Error('原密码和新密码不能相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  re_pwd: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    {
      min: 6,
      max: 15,
      message: '确认密码长度需在 6-15 位之间',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.value.new_pwd) {
          callback(new Error('新密码和确认密码必须一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}



// 提交表单
const handleSubmit = async () => {
    // 触发完整的表单校验
    await pwdFormRef.value.validate()
    await userUpdatePwdService(pwdForm.value)
    ElMessage.success('密码修改成功')
    // 密码修改成功后，退出重新登录
    // 1.清空本地存储的token和个人信息
    userStore.setToken('')
    userStore.setUser({})

    // 拦截到登录界面
    router.push('/login')

}

// 重置表单
const handleReset = () => {
  pwdFormRef.value.resetFields()
}
</script>


<template>
    <page-container title="修改密码">  
  <el-form
    :model="pwdForm"
    :rules="rules"
    ref="pwdFormRef"
    label-width="100px"
    size="medium"
  >
    <!-- 原密码 -->
    <el-form-item label="原密码" prop="old_pwd">
      <el-input
        v-model="pwdForm.old_pwd"
        type="password"
        placeholder="请输入原密码"
      />
    </el-form-item>

    <!-- 新密码 -->
    <el-form-item label="新密码" prop="new_pwd">
      <el-input
        v-model="pwdForm.new_pwd"
        type="password"
        placeholder="请输入新密码"
      />
    </el-form-item>

    <!-- 确认密码 -->
    <el-form-item label="确认密码" prop="re_pwd">
      <el-input
        v-model="pwdForm.re_pwd"
        type="password"
        placeholder="请确认新密码"
      />
    </el-form-item>

    <!-- 操作按钮 -->
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">修改密码</el-button>
      <el-button @click="handleReset">重置</el-button>
    </el-form-item>
  </el-form>
  </page-container>
</template>


<style scoped>
/* 可根据需要添加自定义样式 */
.el-form {
  width: 400px;
  margin: 0 auto;
}
</style>
